package com.yisu.expressway.manager.website.controller;

import com.google.gson.Gson;
import com.yisu.expressway.ewf.common.exception.StageException;
import com.yisu.expressway.ewf.entity.Employee;
import com.yisu.expressway.manager.domain.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

import static com.yisu.expressway.ewf.common.enums.ResponseCode.PARAMETER_ERROR;

/**
 * Created by xlt on 2017/3/21.
 */
public class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    protected <T> T retrieveParameter(HttpServletRequest request, Class<T> clazz) {
        try {
            BufferedReader reader = request.getReader();
            String paramJson = reader.readLine();
            logger.info("param json: [{}]", paramJson);
            T instance = new Gson().fromJson(paramJson, clazz);
            if(instance == null) {
                throw new NullPointerException();
            }
            return instance;
        } catch (Exception e) {
            logger.error("Failed to request, cause: {}-{}", PARAMETER_ERROR.code, PARAMETER_ERROR.msg);
            throw new StageException(PARAMETER_ERROR.code, PARAMETER_ERROR.msg);
        }
    }
    protected Employee getEmployee(HttpServletRequest request) {
        return (Employee)request.getSession().getAttribute(Constants.USER_INFO_KEY);
    }

    protected  String getEmployeeNumber(HttpServletRequest request) {
        Employee employee = getEmployee(request);
        if(employee != null) {
            return employee.getEmployeeNumber();
        }
        return null;
    }

}
